<?php
namespace app\common\controller;
use think\Controller;
use think\Request;
use think\Config;
use think\Validate;
use think\Cache;
use think\Session;


class Base extends Controller
{
    protected $request;//请求
    protected $params;//参数
    protected $module;//模块
    protected $controller;//控制器
    protected $action;//方法
    protected $method;//请求方式
    protected $session;
    protected $url = null;//当前页面完整url
    protected $table = 'empty';//主表
    protected $app = null;//app地址
    protected $common_config = [];//通用配置表
    protected $config = [];  //配置表
    protected $admin = [];//用户信息
    protected $field = [[],false];//数据库查询过滤掉的字段
    protected $fixed = [];//数据库固定不允许修改的部分
    protected $system = [];//通用配置
    protected $privilege = ['create'=>0,'update'=>0,'read'=>0,'delete'=>0]; //权限
    protected $is_login = 0; //是否需要登陆验证和权限挂钩(session)
    protected $is_ajax = 1; //是否是ajax 在iframe里的简单体现
    protected $is_method = ['GET','POST','PUT','DELETE'];
    protected $is_log = 0;//是否开启日志 当时array的时候 里面填写不跟踪的数据

    protected function _initialize(){
        $this->request = Request::instance();//请求
        $this->module = $this->request->module();//模块
        $this->controller = $this->request->controller();//控制器
        $this->action = $this->request->action();//方法
        $this->method = $this->request->method();//请求方式
        $this->url = $this->request->url(true);//完整链接
        $this->session = Session::get();//session
        $config = $this->Config();//控制器附带配置文件
        $this->system = config('SystemConfig');//最上层的公共配置文件
        $this->app = $this->request->domain() . $this->system['App'] . '/public/index.php';//app的链接

        if(isset($config['common'])){
            $this->common_config = $config['common'];//控制器通配
        }
        if(isset($config[$this->action])){
            $this->config = $config[$this->action];//方法配置
        }
        //跨域
        if(isset($this->config['is_cross'])&&$this->config['is_cross']){
            cross();
        }
        else if(isset($this->common_config['is_cross'])&&$this->common_config['is_cross']){
            cross();
        }

        //以下均为无单个方法配置加载通配 若无通配 则返回默认配置
        $this->table = $this->conf('table','empty');
        $this->is_ajax = $this->conf('is_ajax',1);
        $this->is_login = $this->conf('is_login',0);
        $this->is_log = $this->conf('is_log',0);
        $this->field = $this->conf('field',[[],false]);
        $this->fixed = $this->conf('fixed',[]);

        //提供session登录方式
        if(isset($this->session['admin'])){
            $this->admin = $this->session['admin'];
        }
        if($this->is_login==='session'){
            if(!isset($this->session['admin'])||empty($this->session['admin'])){
                if($this->is_ajax){
                    return_msg(0,'登录超时！',[]);
                }
                else{
                    exit('登录超时！');
                }
            }
        }
        //提供cache登录方式|token为所有接口通用参数
        if(isset($this->params['token'])&&!isset($this->session['admin'])) {
            $this->admin = Cache::get($this->params['token']);
        }
        if($this->is_login === 'cache'){
            if(Cache::get($this->params['token'])==false){
                if($this->is_ajax){
                    return_msg(0,'登录超时！');
                }
                else{
                    exit('登录超时！');
                }
            }
            if(!isset($this->params['token'])){
                if($this->is_ajax){
                    return_msg(0,'缺少token！');
                }
                else{
                    exit('缺少token！');
                }
            }
        }
        //公共渲染  移动至最外围
        $this->assign([
            'timestamp'=>time(),
            'system'=>$this->system,
            'url'=>$this->url
        ]);
        $this->privilege();
        $this->params = $this->check_params($this->request->param());




    }
    /**
     * 自动加载模块配置项
     * @param type $model 获取模块
     * @return boolean
     */
    protected function config($controller = null) {
        //加载模块配置文件
        if($controller == null){
            $controller = $this->controller;
        }
        $model_config_file = APP_PATH . $this->module . '/config/' . $controller . '.php';
        if (is_file($model_config_file)) {
            $model_config = require $model_config_file;
            if (!is_array($model_config)) {
                $model_config = [];
            }
            Config::set($controller, $model_config);
            unset($model_config_file);
        } else {
            $model_config = [];
        }
        return $model_config;
    }
    //用于判定文件是否存在后返回数据
    protected function _callback($res,$jump=''){
        if($res){
            return_msg(1,'success',$res,$jump);
        }
        else{
            return_msg(0,'fail',[],$jump);
        }
    }
    //配置函数
    protected function conf($value,$default_config){
        $data = $default_config;
        if(isset($this->config[$value])){
            $data = $this->config[$value];
        }else if(isset($this->common_config[$value])){
            $data = $this->common_config[$value];
        }
        return $data;
    }
    protected function privilege(){
        //用户权限
        if($this->is_login==='session'||$this->is_login==='cache'){
            $admin = $this->admin;
            if(isset($admin['admin_privilege'])&&$admin['admin_privilege']){
                $privilege = $admin['admin_privilege'];
                if($privilege == 'root'){
                    $this->privilege = $this->pri_arr(1,1,1,1);
                }
                else{
                    $privilege = decode($admin['admin_privilege']);
                    if(isset($this->common_config['pri'])&&$this->common_config['pri']){
                        $pri_key  = $this->common_config['pri'];
                    }
                    else{
                        $pri_key = $this->module . '/' . $this->controller ;
                    }
                    $privilege_count = -1;
                    if($privilege){
                        foreach ($privilege as $k=>$v){
                            if($k == $pri_key){
                                $privilege_count = $v;
                            }
                        }
                    }
                    //['增4','改1','查0','删2'] 权值相加;
                    switch ($privilege_count){
                        case -1:
                            $this->privilege = $this->pri_arr(0,0,0,0);//全无
                            break;
                        case 0:
                            $this->privilege =$this->pri_arr(0,0,1,0); //查
                            break;
                        case 1:
                            $this->privilege = $this->pri_arr(0,1,1,0); //查|改
                            break;
                        case 2:
                            $this->privilege = $this->pri_arr(0,0,1,1);//查|删
                            break;
                        case 3:
                            $this->privilege =$this->pri_arr(0,1,1,1);//查|改|删
                            break;
                        case 4:
                            $this->privilege = $this->pri_arr(1,0,1,0);//查|增
                            break;
                        case 5:
                            $this->privilege = $this->pri_arr(1,1,1,0);//查|增|改
                            break;
                        case 6:
                            $this->privilege = $this->pri_arr(1,0,1,1);//查|增|删
                            break;
                        case 7:
                            $this->privilege =$this->pri_arr(1,1,1,1);//查|增|删|改
                            break;
                        default:
                            $this->privilege = $this->pri_arr(0,0,0,0);
                    }
                }
            }
            else{
                $this->privilege = $this->pri_arr(0,0,0,0);
            }
        }
        //自己设置权限
        else if(is_array($this->is_login)){
            $this->privilege = $this->is_login;
        }
        if($this->is_login===0){
            $this->privilege = $this->pri_arr(0,0,1,0);
        }
    }
    //验证参数以及请求方式(通过配置表实现)
    protected function check_params($arr){
        if(isset($this->common_config['validate'])){
            $common_validate =  $this->common_config['validate'];
            if(isset($common_validate['rule'])){
                $rule = $common_validate['rule'];
                if(isset($common_validate['message'])){
                    $message = $common_validate['message'];
                }
                else{
                    $message = [];
                }
                $validater = new Validate($rule,$message);
                if(!$validater->check($arr)){
                    return_msg(0,$validater->getError());
                }
            }
        }

        if(isset($this->config['validate'])){
            $validate =  $this->config['validate'];
            if(isset($validate['rule'])){
                $rule = $validate['rule'];
                if(isset($validate['message'])){
                    $message = $validate['message'];
                }
                else{
                    $message = [];
                }
                $validater = new Validate($rule,$message);
                if(!$validater->check($arr)){
                    return_msg(0,$validater->getError());
                }
            }
        }
        //验证通过
        return $this->check_method($arr);
    }
    //请求方式
    protected function check_method($arr){
        if(isset($this->config['method'])){
            $this->is_method = $this->config['method'];
        }
        else if(isset($this->common_config['method'])){
            $this->is_method = $this->common_config['method'];
        }
        $is_method = $this->is_method;
        $is_exist = false;
        foreach ($is_method as $k => $v){
            if($v == $this->method){
                $is_exist = true;
            }
        }
        if(!$is_exist){
            return_msg(0,'请求方式错误！');
        }
        return $arr;
    }
    //权限值数组
    protected function pri_arr($create,$update,$read,$delete){
        return ['create'=>$create,'update'=>$update,'read'=>$read,'delete'=>$delete];
    }
//  权限的简便使用
    protected function is_pri($action,$is_ajax=1){
        if($action!='create'&&$action!='delete'&&$action!='update'&&$action!='read'){
            if($is_ajax){
                return_msg(0,'权限填写错误！');
            }
            else{
                exit('权限填写错误！');
            }
        }
        if(!$this->privilege[$action]){
            if($is_ajax){
                return_msg(0,'暂无权限！');
            }
            else{
                exit('暂无权限！');
            }
        }
    }

}
